package com.doit.day01;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.ArrayList;
import java.util.List;

public class NameNode {
    ZooKeeper zk = null;

    public void start() throws Exception {
        zk = new ZooKeeper("linux01:2181,linux02:2181,linux03:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("namenode上线了........");
            }
        });
    }

    //监听datanode
    public void listDatanode() throws Exception {
        List<String> ls = zk.getChildren("/datanodes", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    List<String> children = zk.getChildren("/datanodes", this);
                    ArrayList<String> list = new ArrayList<>();

                    for (String child : children) {
                        byte[] data = zk.getData("/datanodes/" + child, null, null);
                        String host = new String(data);
                        list.add(host );
                    }
                    System.out.println(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void  service() throws InterruptedException {
        System.out.println("namenode在服务.....");
        Thread.sleep(Integer.MAX_VALUE);
    }


    public static void main(String[] args) throws Exception {
        NameNode nn = new NameNode() ;
        nn.start();
        nn.listDatanode();
        nn.service();
    }
}
